#!/bin/bash
#
# Create a new SSL keypair and a certificate signature request. Optionally
# self-sign the certificate.
#
# Usage: request_key <site> [self]
# e.g. ./request_key jobs.guardian.co.uk # generate CSR
#      ./request-key jobs.gutest.co.uk self # generate and self-sign
#

echo "######################################"
echo "PLEASE MAKE SURE YOU READ README.FIRST"
echo "######################################"
echo 

site="${1}"

if ! [ -f "${site}.conf" ]; then
	echo "Cannot read config file ${site}.conf"
	exit 1
fi

if [ -e "${site}.pem" ]; then
	# Keep original private key if exists
	openssl req -config "${site}.conf" -new -key "${site}.pem" -out "${site}.csr"
else
	openssl req -config "${site}.conf" -new -keyout "${site}.pem" -out "${site}.csr"
fi

if [ "${2}" = 'self' ]; then
	openssl req -in "${site}.csr" -key "${site}.pem" -x509 -days 730 \
    -out "${site}.crt" -set_serial $(date '+%y')
fi

if [ -e "${site}.csr" ]; then
	echo "DCV Hashes for ${site}.csr"
	echo -n "MD5  : " && openssl req -in "${site}.csr" -outform der | openssl md5 | awk '{ print $2 }'
	echo -n "SHA1 : " && openssl req -in "${site}.csr" -outform der | openssl sha1 | awk '{ print $2 }'
fi
